package cn.echase.ecare.yinfayun.service.impl;

import cn.echase.common.core.enums.ResultCode;
import cn.echase.ecare.yinfayun.domain.dto.OrgBedStatisticsDto;
import cn.echase.ecare.yinfayun.domain.entity.Building;
import cn.echase.ecare.yinfayun.domain.entity.FChargeStandardRelate;
import cn.echase.ecare.yinfayun.domain.mapper.FChargeStandardRelateMapper;
import cn.echase.ecare.yinfayun.domain.mapper.UcBedMapper;
import cn.echase.ecare.yinfayun.domain.vo.OrgBedDetailVo;
import cn.echase.ecare.yinfayun.domain.vo.OrgBedInfoVo;
import cn.echase.ecare.yinfayun.domain.vo.OrgBedItemVo;
import cn.echase.ecare.yinfayun.domain.vo.OrgBedStatisticsVo;
import cn.echase.ecare.yinfayun.service.BuildingService;
import cn.echase.ecare.yinfayun.service.IOrgBedStatisticsService;
import cn.echase.ecare.yinfayun.service.UcElderlyPatientsService;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 床位统计
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class OrgBedStatisticsServiceImpl implements IOrgBedStatisticsService {

    private final UcBedMapper ucBedMapper;
    private final BuildingService buildingService;
    private final UcElderlyPatientsService ucElderlyPatientsService;
    private final FChargeStandardRelateMapper fChargeStandardRelateMapper;


    /**
     * 获取机构的床位信息
     *
     * @param orgBedStatisticsDto 机构id
     * @return 按照床位统计集合
     */
    @Override
    public OrgBedStatisticsVo getOrgBedSummary(OrgBedStatisticsDto orgBedStatisticsDto) {
        String orgId = LoginHelper.getOrgId();

        if (StringUtils.isBlank(orgBedStatisticsDto.getOrgId())) {
            orgBedStatisticsDto.setOrgId(orgId);
        }

        // 获取机构下全部的床位信息
        List<OrgBedInfoVo> dataList = ucBedMapper.selectOrgBedList(orgBedStatisticsDto);

        //获取全部的楼栋和楼层 树形
        List<OrgBedItemVo> list = new ArrayList<>();
        Building building = new Building();
        building.setOrgId(orgId);
        PageHelper.startPage(orgBedStatisticsDto.getPageNum(), orgBedStatisticsDto.getPageSize());
        List<Building> buildingList = buildingService.getList(building);
        if (CollUtil.isNotEmpty(buildingList)) {
            Map<String, List<OrgBedInfoVo>> build = dataList.stream().collect(Collectors.groupingBy(OrgBedInfoVo::getBuildingId));
            //循环处理数据
            if (CollUtil.isNotEmpty(buildingList)) {
                for (Building bd : buildingList) {
                    if (build.get(bd.getUcId()) != null && !build.get(bd.getUcId()).isEmpty()) {
                        list.add(getChildren(bd.getUcId(), build.get(bd.getUcId()), build.size()));
                    }
                }
            }
        }

//        TableDataInfo<OrgBedItemVo> orgBedItemVoTableDataInfo = TableDataInfo.build(ResultCode.SUCCESS.getCode(), list);
//        OrgBedStatisticsVo orgBedStatisticsVo = this.getBedSummary(dataList);
//        orgBedStatisticsVo.setList(orgBedItemVoTableDataInfo);
//        return orgBedStatisticsVo;

        return null; // TODO 需做兼容
    }

    /**
     * 获取楼栋/楼层的床位列表信息
     *
     * @param orgBedStatisticsDto orgBedStatisticsDto
     * @return @return {@link List }<{@link OrgBedDetailVo }>
     */
    @Override
    public TableDataInfo<OrgBedDetailVo> getBedInfoList(OrgBedStatisticsDto orgBedStatisticsDto) {
        orgBedStatisticsDto.setOrgId(LoginHelper.getOrgId());
        // 获取机构下楼栋或者楼层的床位信息
        PageHelper.startPage(orgBedStatisticsDto.getPageNum(), orgBedStatisticsDto.getPageSize());
        List<OrgBedInfoVo> dataList = ucBedMapper.selectOrgBedList(orgBedStatisticsDto);
        if (CollUtil.isEmpty(dataList)) {
//            return TableDataInfo.build(ResultCode.SUCCESS.getCode(), List.of());

            return null; // TODO 需做兼容
        }else {
            boolean singleBuilding = buildingService.isSingleBuilding();

            List<OrgBedDetailVo> bedDetailVos = dataList.stream().map(bedInfoVo -> {
                String bedName;
                if (singleBuilding) {
                    bedName = bedInfoVo.getFloorName() + "-" + bedInfoVo.getRoomName() + "-" + bedInfoVo.getName();
                } else {
                    bedName = bedInfoVo.getBuildingName() + "-" + bedInfoVo.getFloorName() + "-" + bedInfoVo.getRoomName() + "-" + bedInfoVo.getName();
                }
                return OrgBedDetailVo.builder().bedName(bedName)
                        .roomType(getRoomTypeName(bedInfoVo.getRoomId()))
                        .bedStatus(getBedStatusName(bedInfoVo.getBedCheckInStatus()))
                        .elderName(ucElderlyPatientsService.getName(bedInfoVo.getEldId()))
                        .elderId(bedInfoVo.getEldId())
                        .build();
            }).toList();

//            return TableDataInfo.build(ResultCode.SUCCESS.getCode(), bedDetailVos);

            return null; // TODO 需做兼容
        }
    }

    /**
     * 获取机构的床位信息(报表打印的结构)
     *
     * @param orgBedStatisticsDto 机构id
     * @return 按照床位统计集合
     */
    @Override
    public OrgBedStatisticsVo getOrgBedReport(OrgBedStatisticsDto orgBedStatisticsDto) {
        String orgId = LoginHelper.getOrgId();
        if (StringUtils.isBlank(orgBedStatisticsDto.getOrgId())) {
            orgBedStatisticsDto.setOrgId(orgId);
        }
        // 获取机构下全部的床位信息
        List<OrgBedInfoVo> dataList = ucBedMapper.selectOrgBedList(orgBedStatisticsDto);
        Map<String, List<OrgBedInfoVo>> build = dataList.stream().collect(Collectors.groupingBy(OrgBedInfoVo::getBuildingId, LinkedHashMap::new, Collectors.toList()));
        List<OrgBedItemVo> reportList = new ArrayList<>();
        //循环处理数据
        build.forEach((k, v) -> {
            if (v != null && !v.isEmpty()) {
                reportList.addAll(getChildren(k, v, build.size()).getChildren());
            }
        });
        OrgBedStatisticsVo orgBedStatisticsVo = getBedSummary(dataList);
        orgBedStatisticsVo.setReportList(reportList);
        return orgBedStatisticsVo;
    }

    private OrgBedStatisticsVo getBedSummary(List<OrgBedInfoVo> dataList) {
        // 全院总床位数
        long total = dataList.size();
        // 未使用床位数
        long unused = dataList.stream().filter(bedInfoVo -> "0".equals(bedInfoVo.getBedCheckInStatus())).count();
        // 已使用床位数
        long used = total - unused;
        return OrgBedStatisticsVo.builder()
                .totalBedNum(String.valueOf(total))
                .usedBedNum(String.valueOf(used))
                .unusedBedNum(String.valueOf(unused))
                .build();
    }

    private OrgBedItemVo getChildren(String buildId, List<OrgBedInfoVo> v, int buildNum) {
//        v = v.stream().sorted(Comparator.comparing(OrgBedInfoVo::getSort)).collect(Collectors.toList());
        // 全楼床位数
        long buildTotal = v.size();
        // 未使用床位数
        long buildUnused = v.stream().filter(bedInfoVo -> "0".equals(bedInfoVo.getBedCheckInStatus())).count();
        // 已使用床位数
        long buildUsed = buildTotal - buildUnused;
        //单楼栋 = buildNum == 1?"-":
        String buildingName = v.get(0).getBuildingName();
        OrgBedItemVo buildItem = OrgBedItemVo.builder().id(buildId).name(buildingName)
                .bedNum(String.valueOf(buildTotal)).usedBedNum(String.valueOf(buildUsed)).unusedBedNum(String.valueOf(buildUnused)).build();
        Map<String, List<OrgBedInfoVo>> floor = v.stream().collect(Collectors.groupingBy(OrgBedInfoVo::getFloorId, LinkedHashMap::new, Collectors.toList()));
        List<OrgBedItemVo> children = new ArrayList<>();
        floor.forEach((fk, fv) -> {
            // 楼层位数
            long floorTotal = fv.size();
            // 未使用床位数
            long floorUnused = fv.stream().filter(bedInfoVo -> "0".equals(bedInfoVo.getBedCheckInStatus())).count();
            // 已使用床位数
            long floorUsed = floorTotal - floorUnused;
            children.add(OrgBedItemVo.builder().id(fk).name(fv.get(0).getFloorName())
                    .buildingId(buildId).buildingName(buildingName)
                    .bedNum(String.valueOf(floorTotal))
                    .usedBedNum(String.valueOf(floorUsed))
                    .unusedBedNum(String.valueOf(floorUnused))
                    .build());
        });
        buildItem.setChildren(children);
        return buildItem;
    }

    private String getRoomTypeName(String roomId) {
        LambdaQueryWrapper<FChargeStandardRelate> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(FChargeStandardRelate::getTenantId, LoginHelper.getOrgId());
        wrapper.eq(FChargeStandardRelate::getType, 1);
        wrapper.eq(FChargeStandardRelate::getDelFlag, 0);
        wrapper.eq(FChargeStandardRelate::getRelateId, roomId).orderByDesc(FChargeStandardRelate::getCreateTime);
        List<FChargeStandardRelate> fChargeStandardRelateVo = fChargeStandardRelateMapper.selectList(wrapper);
        return fChargeStandardRelateVo.isEmpty() ? "" : fChargeStandardRelateVo.get(0).getStandardName();
    }

    private String getBedStatusName(String bedStatus) {
        // 床位入住情况 0：空闲  1：入住 2：包床 3：预定 4：锁定
        return switch (bedStatus) {
            case "0" -> "空闲";
            case "1" -> "入住";
            case "2" -> "包床";
            case "3" -> "预定";
            case "4" -> "锁定";
            default -> "未知状态";
        };
    }

}
